package org.groupg.project.Indicator;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executors;

public class IndicatorProcessor {
    private static final int BUFFER_SIZE = 1024; // 必须是2的幂次方

    private final Disruptor<IndicatorEvent> disruptor;
    private final RingBuffer<IndicatorEvent> ringBuffer;

    public IndicatorProcessor() {
        // 创建线程池
//        Executor executor = Executors.defaultThreadFactory();

        // 初始化Disruptor
        disruptor = new Disruptor<>(
                new IndicatorEventFactory(),
                BUFFER_SIZE,
                Executors.defaultThreadFactory(),
                ProducerType.MULTI,  // 多生产者模式
                new BlockingWaitStrategy() // 等待策略
        );

        // 设置消费者
        disruptor.handleEventsWith(new IndicatorEventHandler());

        // 启动Disruptor
        ringBuffer = disruptor.start();
    }

    // 发布事件的方法
    public void publishIndicator(String name, Object data) {
        long sequence = ringBuffer.next(); // 获取下一个序列号
        try {
            IndicatorEvent event = ringBuffer.get(sequence);
            event.set(name, data);
        } finally {
            ringBuffer.publish(sequence); // 发布事件
        }
    }

    public void shutdown() {
        disruptor.shutdown();
    }
}